import React, { useContext, useState, useEffect, useRef } from 'react';
import {
  message,
  Button,
  Table,
  Spin,
  Modal,
  Form,
  Input,
  InputNumber,
  DatePicker,
  Popconfirm,
} from 'antd';
import {
  getMappingByTableid,
  starUpdateData,
  restarTask,
  stopwork,
  starUpdateDelflag,
} from '../api';

const { RangePicker } = DatePicker;
const SetTask = props => {
  // 结构化数据
  const { visible, onCancel, onSuccess, data, type } = props;

  const dataList = [];
  const columns = [
    {
      title: 'Name',
      dataIndex: 'name',
      key: 'name',
      render: text => <a>{text}</a>,
    },
    {
      title: 'Age',
      dataIndex: 'age',
      key: 'age',
    },
    {
      title: 'Address',
      dataIndex: 'address',
      key: 'address',
    },
  ];
  // 初始化 form
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [flag, setFlag] = useState(0);

  const showModal = () => {
    setIsModalVisible(true);
  };

  // 归集数据
  const handleOk = () => {
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  // 详情
  const getDetailData = () => {
    const paylaod = {
      id: data.id,
    };
    setLoading(true);
    getMappingByTableid(paylaod).then(res => {
      setLoading(false);
      if (res.code === 0) {
        setItemId(res.data.id);
        const structure = res.data.structures || [];
        setListData(structure);
      } else {
        message.error(res.msg || '获取详情失败');
      }
    });
  };

  //  归集库设置
  const setStarUpdateData = () => {
    form.validateFields().then(values => {
      const paylaod = {
        id: data.id,
        flag,
        last: values.time && values.time[0] ? values.time[0] : '',
        max: values.time && values.time[1] ? values.time[1] : '',
      };
      setLoading(true);
      starUpdateData({ ...values, ...paylaod }).then(res => {
        setLoading(false);
        if (res.code === 0) {
          setIsModalVisible(false);
          message.success(res.msg || '操作成功');
        } else {
          message.error(res.msg || '操作失败');
        }
      });
    });
  };

  useEffect(() => {
    if (visible === true) {
      form.setFieldsValue({ pagelength: 500, startblock: 0, startpage: 0 });
    }
  }, [visible]);

  // 栅格化
  const formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 18 },
  };

  // 任务续传
  const setRestarTask = () => {
    setLoading(true);
    restarTask({ id: data.id }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success(res.msg || '操作成功');
      } else {
        message.error(res.msg || '操作失败');
      }
    });
  };
  // 任务续传
  const setStarUpdateDelflag = () => {
    setLoading(true);
    starUpdateDelflag({ id: data.id }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success(res.msg || '操作成功');
      } else {
        message.error(res.msg || '操作失败');
      }
    });
  };
  // 强制结束
  const setstopwork = () => {
    setLoading(true);
    stopwork({ id: data.id }).then(res => {
      setLoading(false);
      if (res.code === 0) {
        message.success(res.msg || '操作成功');
      } else {
        message.error(res.msg || '操作失败');
      }
    });
  };

  const save = async () => {
    // try {
    //   const values = await form.validateFields();
    //   toggleEdit();
    //   handleSave({ ...record, ...values });
    // } catch (errInfo) {
    //   console.log('Save failed:', errInfo);
    // }
  };

  return (
    <Spin spinning={loading}>
      <table border="1" style={{ width: '90%' }}>
        <tbody>
          <tr>
            <td>当前状态：</td>
            <td colSpan="3"></td>
          </tr>
          <tr>
            <td width="100px">开始时间：</td>
            <td></td>
            <td width="100px">最新时间：</td>
            <td></td>
          </tr>
          <tr>
            <td>任务指令：</td>
            <td></td>
            <td width="100px">每页行数：</td>
            <td></td>
          </tr>
          <tr>
            <td>传递页数：</td>
            <td>/()</td>
            <td>传递片数：</td>
            <td>/()</td>
          </tr>
          <tr>
            <td>传递总量：</td>
            <td></td>
            <td>接收数量：</td>
            <td></td>
          </tr>
          <tr>
            <td>起始时间戳：</td>
            <td></td>
            <td>截至时间戳：</td>
            <td></td>
          </tr>
        </tbody>
      </table>
      <div style={{ margin: 30 }}>
        <Button type="primary" onClick={() => showModal(0)} style={{ marginLeft: 20 }}>
          归集数据
        </Button>
        <Popconfirm
          placement="topRight"
          title="确定任务续传吗？"
          onConfirm={setRestarTask}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" style={{ marginLeft: 20 }}>
            任务续传
          </Button>
        </Popconfirm>
        <Popconfirm
          placement="topRight"
          title="确定校准数据吗？"
          onConfirm={setStarUpdateDelflag}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" style={{ marginLeft: 20 }}>
            校准数据
          </Button>
        </Popconfirm>

        <Button type="primary" onClick={() => showModal(1)} style={{ marginLeft: 20 }}>
          归集并校准
        </Button>

        <Popconfirm
          placement="topRight"
          title="确定强制结束吗？"
          onConfirm={setstopwork}
          okText="确定"
          cancelText="取消"
        >
          <Button type="primary" danger style={{ marginLeft: 20 }}>
            强制结束
          </Button>
        </Popconfirm>
      </div>
      <Table columns={columns} dataSource={dataList} bordered />
      <Modal
        title="启动数据收集任务"
        visible={isModalVisible}
        onOk={setStarUpdateData}
        onCancel={handleCancel}
        width={600}
      >
        {/* "flag": "", "id": "", "last": "", "max": "", "pagelength": 0, "startblock": 0, "startpage":
        0 */}
        <Form {...formItemLayout} name="control-ref" form={form}>
          <Form.Item label="数据起始片" name="startblock" rules={[{ required: true }]}>
            <InputNumber style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="数据起始页" name="startpage" rules={[{ required: true }]}>
            <InputNumber style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="每页条数" name="pagelength" rules={[{ required: true }]}>
            <InputNumber style={{ width: 200 }} />
          </Form.Item>
          <Form.Item label="时间戳" name="time">
            <RangePicker showTime format="YYYY-MM-DD HH:mm:ss" />
          </Form.Item>
        </Form>
      </Modal>
    </Spin>
  );
};

export default SetTask;
